/**
 * @flow
 * @providesModule SegmentedControl
 * 
 * 增强的多页签组件，支持多种样式和动画效果
 * 
 * 使用示例:
 * 
 * // 默认样式 - 紧凑模式
 * <SegmentedControl
 *   values={['全部', '进行中', '已完成']}
 *   selectedIndex={0}
 *   onChange={(index) => setSelectedIndex(index)}
 *   compact={true}
 *   animated={true}
 * />
 * 
 * // 药丸样式 - 滑动背景效果
 * <SegmentedControl
 *   type="pill"
 *   values={['推荐', '最新', '热门']}
 *   selectedIndex={1}
 *   selectionColor="#FF6B6B"
 *   onChange={(index) => setSelectedIndex(index)}
 * />
 * 
 * // 卡片样式 - 立体感效果
 * <SegmentedControl
 *   type="card"
 *   values={['选项1', '选项2', '选项3']}
 *   selectedIndex={0}
 *   selectionColor="#4ECDC4"
 *   onChange={(index) => setSelectedIndex(index)}
 * />
 * 
 * // 下划线样式
 * <SegmentedControl
 *   type="underline"
 *   values={['首页', '发现', '我的']}
 *   selectedIndex={0}
 *   selectionColor="#45B7D1"
 *   onChange={(index) => setSelectedIndex(index)}
 * />
 */

import React, { useRef, useEffect } from 'react';
import { 
  Text, 
  StyleSheet, 
  TouchableOpacity, 
  View, 
  Animated
} from 'react-native';
import { colors, spacing, typography, shadows } from '../styles';

interface SegmentedControlProps {
  type?: 'default' | 'underline' | 'pill' | 'card';
  values: Array<string>;
  selectedIndex: number;
  selectionColor?: string;
  style?: any;
  onChange: (index: number) => void;
  animated?: boolean;
  compact?: boolean;
  size?: 'small' | 'medium' | 'large';
}
interface SegmentProps {
  isSelected?: boolean;
  selectionColor?: string;
  value?: string;
  type?: 'default' | 'underline' | 'pill' | 'card';
  onPress?: () => void;
  index?: number;
  totalSegments?: number;
  animated?: boolean;
  compact?: boolean;
  onLayout?: (index: number, layout: {x: number, width: number}) => void;
  size?: 'small' | 'medium' | 'large';
}
const SegmentedControl: React.FC<SegmentedControlProps> = ({
  type = 'default',
  values,
  selectedIndex,
  selectionColor = colors.primary,
  onChange,
  style,
  animated = true,
  compact = true,
  size = 'medium',
}) => {
  const animatedValue = useRef(new Animated.Value(selectedIndex)).current;
  const scaleValue = useRef(new Animated.Value(1)).current;
  const [_containerWidth, setContainerWidth] = React.useState(0);
  const [segmentLayouts, setSegmentLayouts] = React.useState<Array<{x: number, width: number}>>([]);
  const segmentRefs = useRef<Array<View | null>>([]);

  // 根据size属性计算高度
  const getHeight = () => {
    switch (size) {
      case 'small':
        return 30;
      case 'large':
        return 50;
      case 'medium':
      default:
        return 40;
    }
  };

  useEffect(() => {
    if (animated) {
      Animated.parallel([
        Animated.spring(animatedValue, {
          toValue: selectedIndex,
          useNativeDriver: false,
          tension: 100,
          friction: 8,
        }),
        Animated.sequence([
          Animated.timing(scaleValue, {
            toValue: 0.95,
            duration: 100,
            useNativeDriver: true,
          }),
          Animated.timing(scaleValue, {
            toValue: 1,
            duration: 100,
            useNativeDriver: true,
          }),
        ]),
      ]).start();
    }
  }, [selectedIndex, animated, animatedValue, scaleValue]);

  const handleSegmentLayout = (index: number, layout: {x: number, width: number}) => {
    setSegmentLayouts(prev => {
      const newLayouts = [...prev];
      newLayouts[index] = layout;
      return newLayouts;
    });
  };

  const segments = values.map((value: string, index: number) => (
    <Segment
      type={type}
      key={value}
      value={value}
      index={index}
      totalSegments={values.length}
      isSelected={index === selectedIndex}
      selectionColor={selectionColor}
      onPress={() => onChange(index)}
      animated={animated}
      compact={compact}
      size={size}
      onLayout={type === 'pill' ? handleSegmentLayout : undefined}
      ref={(ref) => {
        if (segmentRefs.current) {
          segmentRefs.current[index] = ref;
        }
      }}
    />
  ));

  const containerStyle = [
    styles.container,
    compact && type !== 'pill' && styles.compactContainer,
    type === 'pill' && [styles.pillContainer, { height: getHeight() + spacing.padding.xs * 2 }],
    type === 'card' && styles.cardContainer,
    style,
  ];

  return (
    <Animated.View 
      style={[containerStyle, { transform: [{ scale: scaleValue }] }]}
      onLayout={(event) => {
        if (type === 'pill') {
          setContainerWidth(event.nativeEvent.layout.width);
        }
      }}
    >
      {type === 'pill' && segmentLayouts.length === values.length && segmentLayouts.every(layout => layout) && (
        <Animated.View
          style={[
            styles.pillBackground,
            {
              backgroundColor: selectionColor,
              height: getHeight(),
              width: animatedValue.interpolate({
                inputRange: values.map((_, index) => index),
                outputRange: segmentLayouts.map(layout => layout.width),
                extrapolate: 'clamp',
              }),
              left: spacing.padding.xs,
              transform: [
                {
                  translateX: animatedValue.interpolate({
                    inputRange: values.map((_, index) => index),
                    outputRange: segmentLayouts.map(layout => layout.x),
                    extrapolate: 'clamp',
                  }),
                },
              ],
            },
          ]}
        />
      )}
      {segments}
    </Animated.View>
  );
};

const Segment = React.forwardRef<View, SegmentProps>(({
  isSelected,
  onPress,
  selectionColor = colors.primary,
  value,
  type = 'default',
  index = 0,
  animated = true,
  compact = true,
  size = 'medium',
  onLayout,
}, ref) => {
  const scaleAnim = useRef(new Animated.Value(1)).current;
  const opacityAnim = useRef(new Animated.Value(isSelected ? 1 : 0.7)).current;

  const getHeight = () => {
    switch (size) {
      case 'small':
        return 30;
      case 'large':
        return 50;
      case 'medium':
      default:
        return 40;
    }
  };

  const height = getHeight();

  useEffect(() => {
    if (animated) {
      Animated.parallel([
        Animated.spring(scaleAnim, {
          toValue: isSelected ? 1.05 : 1,
          useNativeDriver: true,
          tension: 100,
          friction: 8,
        }),
        Animated.timing(opacityAnim, {
          toValue: isSelected ? 1 : 0.7,
          duration: 200,
          useNativeDriver: true,
        }),
      ]).start();
    }
  }, [isSelected, animated, scaleAnim, opacityAnim]);

  const getButtonStyle = () => {
    const baseStyle: any[] = [styles.button];
    
    switch (type) {
      case 'pill':
        baseStyle.push([styles.pillButton, { height, minHeight: height }]);
        if (isSelected) {
          baseStyle.push({ backgroundColor: 'transparent' });
        }
        break;
      case 'card':
        baseStyle.push([styles.cardButton, { height: height + 8 }]);
        if (isSelected) {
          baseStyle.push(styles.cardButtonSelected);
        }
        break;
      case 'underline':
        baseStyle.push([styles.underlineButton, { height }]);
        if (isSelected) {
          baseStyle.push({ borderBottomColor: selectionColor });
        }
        break;
      default:
        baseStyle.push([styles.defaultButton, { height }]);
        if (isSelected) {
          baseStyle.push({ borderColor: selectionColor, backgroundColor: selectionColor + '15' });
        }
    }

    // 紧凑模式下的特殊样式
    if (compact && type !== 'pill') {
      baseStyle.push([styles.compactButton, { height: height - 8 }]);
    }

    return baseStyle;
  };

  const getLabelStyle = () => {
    const baseStyle: any[] = [styles.label];
    
    // 根据size调整字体大小
    if (size === 'small') {
      baseStyle.push(typography.caption.small);
    } else if (size === 'large') {
      baseStyle.push(typography.body.medium);
    } else {
      baseStyle.push(typography.caption.small);
    }
    
    if (isSelected) {
      baseStyle.push(styles.selectedLabel);
      if (type === 'pill') {
        baseStyle.push({ color: colors.white });
      } else {
        baseStyle.push({ color: selectionColor });
      }
    } else {
      baseStyle.push(styles.deselectedLabel);
    }

    return baseStyle;
  };

  const title = value && value.toUpperCase();
  const accessibilityState = { selected: isSelected };

  return (
    <Animated.View
      ref={ref}
      style={[
        { transform: [{ scale: scaleAnim }], opacity: opacityAnim },
        type === 'pill' ? styles.adaptiveSegment : (compact && styles.compactSegment),
      ]}
      onLayout={onLayout ? (event) => {
        const { x, width } = event.nativeEvent.layout;
        onLayout(index, { x, width });
      } : undefined}
    >
      <TouchableOpacity
        accessibilityState={accessibilityState}
        activeOpacity={0.6}
        onPress={onPress}
        style={getButtonStyle()}
        onPressIn={() => {
          if (animated) {
            Animated.spring(scaleAnim, {
              toValue: 0.95,
              useNativeDriver: true,
              tension: 300,
              friction: 10,
            }).start();
          }
        }}
        onPressOut={() => {
          if (animated) {
            Animated.spring(scaleAnim, {
              toValue: isSelected ? 1.05 : 1,
              useNativeDriver: true,
              tension: 300,
              friction: 10,
            }).start();
          }
        }}
      >
        <Text style={getLabelStyle()}>{title}</Text>
        {type === 'card' && isSelected && (
          <View style={[styles.cardIndicator, { backgroundColor: selectionColor }]} />
        )}
      </TouchableOpacity>
    </Animated.View>
  );
});


const styles = StyleSheet.create({
  // 容器样式
  container: {
    flexDirection: 'row',
    backgroundColor: 'transparent',
    alignItems: 'center',
  },
  compactContainer: {
    padding: spacing.padding.xs,
    backgroundColor: colors.light,
    borderRadius: spacing.radii.lg,
    ...shadows.sm,
  },
  pillContainer: {
    backgroundColor: colors.light,
    borderRadius: spacing.radii.full,
    padding: spacing.padding.xs,
    position: 'relative',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-start',
    alignSelf: 'flex-start',
    ...shadows.base,
  },
  cardContainer: {
    backgroundColor: 'transparent',
    gap: spacing.sizes['2'],
    padding: spacing.padding.xs,
  },

  // 背景动画元素
  pillBackground: {
    position: 'absolute',
    top: spacing.padding.xs,
    bottom: spacing.padding.xs,
    borderRadius: spacing.radii.full,
    ...shadows.sm,
  },

  // 按钮基础样式
  button: {
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
    position: 'relative',
    overflow: 'hidden',
  },

  // 默认按钮样式
  defaultButton: {
    paddingHorizontal: spacing.padding.sm,
    borderRadius: spacing.radii.lg,
    borderWidth: 2,
    borderColor: colors.border.primary,
    backgroundColor: colors.white,
    ...shadows.sm,
  },

  // 紧凑按钮样式
  compactButton: {
    paddingHorizontal: spacing.padding.xs,
    borderRadius: spacing.radii.md,
    marginHorizontal: spacing.margin.xs,
  },

  // 药丸按钮样式
  pillButton: {
    paddingHorizontal: spacing.padding.sm,
    borderRadius: spacing.radii.full,
    backgroundColor: 'transparent',
    zIndex: 1,
    alignSelf: 'flex-start',
    alignItems: 'center',
    justifyContent: 'center',
    minWidth: 'auto',
  },

  // 卡片按钮样式
  cardButton: {
    paddingHorizontal: spacing.padding.md,
    paddingVertical: spacing.padding.sm,
    borderRadius: spacing.radii.lg,
    backgroundColor: colors.white,
    borderWidth: 1,
    borderColor: colors.border.primary,
    ...shadows.sm,
    minWidth: 60,
  },
  cardButtonSelected: {
    borderColor: colors.primary,
    backgroundColor: colors.primaryLight,
    ...shadows.base,
    transform: [{ translateY: -1 }],
  },

  // 下划线按钮样式
  underlineButton: {
    paddingBottom: spacing.padding.sm,
    paddingHorizontal: spacing.padding.md,
    borderBottomWidth: 3,
    borderBottomColor: 'transparent',
    marginRight: spacing.margin.md,
    backgroundColor: 'transparent',
  },

  // 紧凑段样式
  compactSegment: {
    flex: 1,
  },
  // 自适应段样式（用于pill类型）
  adaptiveSegment: {
    flex: 0,
  },

  // 文字样式
  label: {
    fontWeight: '600',
    textAlign: 'center',
  },
  selectedLabel: {
    fontWeight: '700',
  },
  deselectedLabel: {
    color: colors.text.secondary,
  },

  // 卡片指示器
  cardIndicator: {
    position: 'absolute',
    bottom: 0,
    left: '50%',
    marginLeft: -8,
    width: 16,
    height: 3,
    borderRadius: spacing.radii.sm,
  },
});

export default SegmentedControl;
